#' TVAR Estimation
#' @param regdata a data frame which include \code{ID, Time, cpi, gdp, TFP, unctn}
#' @param thresholdvar
#'

TGVAR <- function(regdata,endovar, thrsholdvar = 'gdp', trim = 0.3, p = 2, q = 1){
  countryrlt <- list()
  # ADFtest <- NULL
  for (country in unique(regdata$ID)) {
    med <- ReadySingleCountry(regdata, FV, country = country, endovar = endovar)
    vardata <- med[['vardata']]
    ADFtest <- med[['ADF']]

    # order threshold variable
    OrderThr <- sort(vardata[,thrsholdvar])

    ifelse (country %in% 'USA',
            endovar_tmp <- c(endovar, 'unctn'),
            endovar_tmp <- endovar)

    # lag exogen variables
    exogen <- exogen_med <- dplyr::select(vardata, -all_of(endovar_tmp))
    for (i in 1:q) {
      tmp <- apply(exogen_med, 2,dplyr::lag, n = i)
      colnames(tmp) <- paste(colnames(tmp),as.character(i),sep = '')
      colnames(tmp) <- str_remove(colnames(tmp),'0')
      exogen <- cbind(exogen,tmp)
    }

    # 全样本估计
    rawrlt <- tsDyn::lineVar(vardata[,endovar_tmp], lag = p, include = 'const', exogen = exogen)
    thrrlt <- updwEst(vardata, OrderThr, endovar_tmp, thrsholdvar,exogen, p, trim)
    LR <- nrow(residuals(rawrlt)) * (log(det(cov(residuals(rawrlt)))) - min(thrrlt$tmpaic))
    # browser()
    pvalue <- 1 - pchisq(LR, df = p * length(endovar)^2 + length(endovar) * length(exogen) * (q + 1))

    # 阈值模型好则存阈值模型
    ifelse (pvalue < 0.05,
            countryrlt[[country]] <- list(dn = thrrlt$tvarrlt[[which.min(thrrlt$tmpaic)]]$dn,
                                          up = thrrlt$tvarrlt[[which.min(thrrlt$tmpaic)]]$up,
                                          thr = thrrlt$tvarrlt[[which.min(thrrlt$tmpaic)]]$thr,
                                          LR = LR,
                                          pvalue = pvalue,
                                          ADFtest = ADFtest),
            countryrlt[[country]] <- list(rawrlt = VAR(vardata[,endovar_tmp],
                                                       p = p,type = 'const', exogen = exogen),
                                          LR = LR,
                                          pvalue = pvalue,
                                          ADFtest = ADFtest))
  }
  return(countryrlt)
}


